<?php
//declare (strict_types=1);

/**
 * @Description:
 * @Author: Chern
 * @Date: 2023/7/10
 * @Time: 10:38
 */

namespace app\controller;

use app\BaseController;
use app\branch;
use app\databaseField;
use app\message;
use app\model\CluePerson;
use app\model\SystemCertificate;
use app\model\SystemDynamicFrom;
use app\model\SystemDynamicFromField;
use app\model\SystemFieldPower;
use app\model\SystemFieldRandPower;
use app\model\SystemMenuDataPower;
use app\model\SystemNotice;
use app\model\SystemOperateLog;
use app\model\SystemMenu;
use app\model\User;
use app\model\UserOrganization;
use app\model\UserPosition;
use app\Request;
use app\service\Power;
use app\service\System;
use app\service\User as UserServer;
use app\stateData;
use app\validate\DynamicFrom;
use app\validate\Menu;
use app\validate\User as UserV;
use Exception;
use ReflectionClass;
use think\App;
use think\Db;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Db as DbAlias;
use think\facade\Filesystem;
use think\facade\Validate;
use think\Log;
use think\Model;
use function Symfony\Component\VarDumper\Dumper\esc;

/**
 * 系统设置控制器
 **/
class SystemSettings extends BaseController
{
    private $operateLog;

    private $systemMenu;//菜单管理表

    private $systemDynamicFrom;//动态菜单表

    private $systemDynamicFromField;//字段表

    private $systemFieldPower; //字段权限缓存表

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->operateLog = new SystemOperateLog();

        $this->systemMenu = new SystemMenu();

        $this->systemDynamicFrom = new SystemDynamicFrom();

        $this->systemDynamicFromField = new SystemDynamicFromField();

        $this->systemFieldPower = new SystemFieldPower();
    }

    /**
     * 系统信息
     * 获取系统信息
     */
    public function getSettingsInfo(User $model, Request $request,UserServer $userServer)
    {
        $uid = $request->get('user_login_id');

        $result = $model->getIdUserData($uid);
        $result['enter_name'] = $userServer->getUserEnterName($result);
//        $result['logo'] = $result && $result['logo'] ? str_replace('\\', '/', 'http://' . $_SERVER['HTTP_HOST'] .'/storage/' . $result['logo']) : 'http://' . $_SERVER['HTTP_HOST'].'/'.branch::$default_logo;
        $result['logo'] = $userServer->getUserLogo($result);
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    /**
     * 系统信息
     * 系统信息修改
     * @param Request $request
     */
    public function settingsInfo(Request $request, User $model)
    {
        $param = $request->post();
        $param['id'] = $request->param('user_login_id');
        $file = $request->file('image');

        $allowed_types = array('jpg', 'jpeg', 'png');


        if (empty($file)) {
            unset($param['image']);
        }else{
            if (!in_array($file->extension(), $allowed_types, true)) {

                return ReJson(message::$ERROR_CODE, message::$ERR_IMG_FORMAT);
            }
        }

        try {

            if ($file) {
                // 上传到本地服务器
                $param['logo'] = \think\facade\Filesystem::disk('public')->putFile( 'file', $file);
            }

            $result = $model->getIdUserData($param['id']);

            if ($result['password'] == $param['password']) {

                unset($param['password']);
            }

            $model->systemSave($param);

            $this->operateLog->addOperate($request->param('user_login_id'), message::$Log_SYSTEM_SETTINGS, message::$SYSTEM_SETTINGS_INFO_SUCC);

        } catch (\Exception $exception) {
            return ReJson(message::$ERROR_CODE, $exception->getMessage());
        }

        return ReJson(message::$SUCC_CODE, message::$SYSTEM_SETTINGS_INFO_SUCC);
    }

    /**
     * 分支管理
     * 查询分公司账号
     */

    public function branchCompany(Request $request, User $model)
    {
        /**
         * @param $page
         */

        $page = $request->get('page') ?: 1;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;

        $like = $request->get('where') ?: '';

        $result = $model->getUserInfo(stateData::$_company_type['branch_company'], $pageNum, $page, $like);

        $pages['total'] = $model->getUserTypeCount(stateData::$_company_type['branch_company']); //获取总条数

        $pages['pageNumber'] = $pageNum; //每页显示多少条

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result, $pages);
    }


    /**
     * 分支管理
     * 添加分支账号
     * @param Request $request
     */
    public function addBranchCompany(Request $request, User $model)
    {
        $param = $request->post();

        try {

            validate(UserV::class)->scene('add')->check($param);

            //设置默认密码
            $param['password'] = stateData::$_password;
            if(!isset($param['branch_department_id'])){
                return ReJson(message::$ERROR_CODE, message::$BRANCH_DEPARTMENT_ID_NULL);
            }
            $param['department_id'] = $param['branch_department_id'];
            unset($param['branch_department_id']);
            $check = $model->checkUniqueName($param['username']);
            if (!$check) {
                return ReJson(message::$ERROR_CODE, message::$ERR_SYSTEM_NAME_REPEAT);
            }
            $branch_department_check = $model->checkUniqueBranchDepartment($param['department_id']);
            if(!$branch_department_check){
                return ReJson(message::$ERROR_CODE, message::$BRANCH_DEPARTMENT_ID_REPEAT);
            }
            $result = $model->addBranchCompanyAccount($param, stateData::$_company_type['branch_company']);

        } catch (ValidateException $e) {

            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        if ($result) {

            $this->operateLog->addOperate($request->param('user_login_id'), message::$BRANCH, message::$SUCC_SYSTEM_UPDATE_FZGL);

            return ReJson(message::$SUCC_CODE, message::$ERR_SYSTEM_ADD_FZGL);
        }

        return ReJson(message::$ERROR_CODE, message::$ERR_SYSTEM_ADD_FZGL);

    }

    /**
     * 分支管理
     * 分支账号编辑
     */
    public function editBranchCompany(Request $request, User $model)
    {
        $param = $request->post([
            'id',
            'nickname',
            'username',
            'create_date',
            'describe',
            'branch_department_id'
        ]);

        try {

            validate(UserV::class)->check($param);

        } catch (ValidateException $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        if(!isset($param['branch_department_id'])){
            return ReJson(message::$ERROR_CODE, message::$BRANCH_DEPARTMENT_ID_NULL);
        }
        $param['department_id'] = $param['branch_department_id'];
        unset($param['branch_department_id']);
        $check = $model->checkUniqueName($param['username'],$param['id']);
        if (!$check) {
            return ReJson(message::$ERROR_CODE, message::$ERR_SYSTEM_NAME_REPEAT);
        }
        $branch_department_check = $model->checkUniqueBranchDepartment($param['department_id'],$param['id']);
        if(!$branch_department_check){
            return ReJson(message::$ERROR_CODE, message::$BRANCH_DEPARTMENT_ID_REPEAT);
        }
        $result = $model->editBranchCompanyInfo($param);

        if ($result) {
            $this->operateLog->addOperate($request->param('user_login_id'), message::$BRANCH, message::$SUCC_SYSTEM_ADD_FZGL);
            return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE_DATA);
        }

        return ReJson(message::$ERROR_CODE, message::$ERR_UPDATE_DATA);

    }

    /**
     * 分支管理
     * 重置密码
     */
    public function reBranchPassword(Request $request, User $model)
    {
        $id = $request->post('id');

        $result = $model->rePassword($id, stateData::$_password);

        if ($result) {

            $this->operateLog->addOperate($request->param('user_login_id'), message::$RERSON, message::$SUCC_SYSTEM_REPASSWORD);

            return ReJson(message::$SUCC_CODE, message::$SUCC_REPASS);
        }

        return ReJson(message::$ERROR_CODE, message::$ERR_REPASS);

    }

    /**
     * 分支管理
     * 删除账号
     */
    public function delBranch(Request $request, System $systemService, User $model)
    {

        if (!$request->post('id')) {
            return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        }

        $id = $systemService->analysisId($request->post('id'));

        $result = $model->delBranchAccount($id);

        if ($result) {

            $this->operateLog->addOperate($request->param('user_login_id'), message::$RERSON, message::$SUCC_SYSTEM_DEL_ACCOUNT);

            return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
        }

        return ReJson(message::$ERROR_CODE, message::$ERR_DATELE_DATA);

    }

    /**
     * 启用|禁用
     */
    public function isED(Request $request, User $model)
    {
        $param = $request->post();

        try {

            Validate(\app\validate\SystemDynamicFromField::class)->scene('eDField')->check($param);

            $model->editBranchCompanyInfo($param);

        } catch (ValidateException $e) {
            $this->operateLog->addOperate($request->param('user_login_id'), message::$RERSON, message::$SUCC_SYSTEM_STATUS_DE);

            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    /*****************************************************************菜单管理****************************************************************/

    //查询所有菜单
    public function getMenuList(System $systemService, Request $request)
    {
        $where = $request->get('where') ?: '';

        $menuList = $systemService->menuTreeList($this->systemMenu->getMenuList($where));

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $menuList);
    }

    //添加菜单
    public function addMenu(Request $request)
    {
        /**
         * @param $type
         * @param $parent_id //选填
         * @param $alias_id
         * @param $menu_name
         * @param $route_url //选填
         * @param $file
         * @param $menu_level
         */

        $param = $request->post();

        $menu_icon = Config::get('file.menu_icon');

        $file = $request->file('file');

        try {
            //验证图标
//            Validate(Menu::class)->scene('files')->check(['file'=>$file]);

            if (!empty($file)) {
                $param['menu_icon'] = Filesystem::disk('public')->putfile($menu_icon, $file);
            }

//            Validate(Menu::class)->check($param);
            if(empty($param['alias_id'])){
                return ReJson (message::$ERROR_CODE,message::$SYSTEM_MENU_ALIAS_EMPTY);
            }

            //判断别名alias_id是否存在 存在返回不让添加
            $asId = $this->systemMenu->getAliasIdModel($param['alias_id']);

            if ($asId) return ReJson(message::$ERROR_CODE, message::$ERR_ALIAS_EXIST);

            $result = $this->systemMenu->addMenuModel($param);

        } catch (ValidateException $e) {
            return ReJson(message::$SUCC_CODE, $e->getMessage());
        }

        if ($result) {
            $this->operateLog->addOperate($request->param('user_login_id'), message::$MENU, message::$SUCC_SYSTEM_ADD_MENU);
            return ReJson(message::$SUCC_CODE, message::$SUCC_INSERT_DATA);
        }
        return ReJson(message::$ERROR_CODE, message::$ERR_INSERT_DATA);

    }

    //修改编辑菜单
    public function editMenu(Request $request)
    {
        /**
         * @param $id
         * @param $type
         * @param $parent_id //选填
         * @param $alias_id
         * @param $menu_name
         * @param $route_url //选填
         * @param $file
         * @param $menu_level
         */

        $param = $request->post();

        $menu_icon = Config::get('file.menu_icon');

        $file = $request->file('file');

        try {
            //验证图标
//            Validate(Menu::class)->scene('files')->check(['file'=>$file]);
//
//            Validate(Menu::class)->scene('edit')->check($param);

            if (!empty($file)) {
                $param['menu_icon'] = Filesystem::disk('public')->putfile($menu_icon, $file);
            }

            $result = $this->systemMenu->updateMenuModel($param);

        } catch (ValidateException $e) {
            return ReJson(message::$SUCC_CODE, $e->getMessage());
        }

        if ($result) {
            $this->operateLog->addOperate($request->param('user_login_id'), message::$MENU, message::$SUCC_SYSTEM_UPDATE_MENU);
            return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
        }
        return ReJson(message::$ERROR_CODE, message::$ERR_UPDATE);
    }

    //删除|批量删除菜单
    public function delMenu(Request $request, System $systemService)
    {
        /**
         * @param $id
         */
        $id = $request->post('id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //查询是否有子菜单
        if ($this->systemMenu->getSonMenu($id)) {
            return ReJson(message::$ERROR_CODE, message::$ERR_DELETE_SON_MENU);
        }

        $result = $this->systemMenu->delMenuModel($systemService->analysisId($id));

        if ($result) {
            $this->operateLog->addOperate($request->param('user_login_id'), message::$MENU, message::$SUCC_SYSTEM_DELETE_MENU);

            return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
        }

        return ReJson(message::$ERROR_CODE, message::$ERR_DATELE_DATA);
    }


    /**********************************************************************************动态表单数据*************************************************************************/

    //查询动态表单数据列表
    public function getFromDataList(Request $request, System $systemService)
    {

        /**
         * @param $page
         */
        $page = $request->get('page') ?: 1;
        $pageNum = $request->get('pageNum') ?:stateData::$_page;

        $where = $request->get('where') ?: '';

        if (empty($page)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $result = $this->systemDynamicFrom->getFromList($page,$pageNum, $where);
        //循环找alias_id对应name
        $aliasName = [];

        foreach ($result as $i => $iValue) {

            $aliasName = $this->systemMenu->getMenuName($systemService->analysisId($iValue['alias_id']));

            foreach ($aliasName as $yValue) {

                $result[$i]['alias_name'] .= $yValue['menu_name'] . ',';
            }
        }

        $pages['total'] = $this->systemDynamicFrom->getFromCount();

        $pages['pageNumber'] = stateData::$_page;

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result, $pages);

    }

    //编辑动态表单数据
    public function editFromData(Request $request, System $system)
    {
        /**
         * 参数
         * @param $id
         * @param $template_name
         * @param $type
         * @param $alias_id //关联menu表alias_id ","分割
         *
         */
        $param = $request->post();
//        \think\facade\Log::error ($param);
        DbAlias::startTrans();
        try {

            $ReflectionClass = new ReflectionClass(databaseField::class);

            $data = $ReflectionClass->getStaticPropertyValue($param['alias_id'], false);

            if (!$data) {
                return ReJson(message::$ERROR_CODE, message::$ERR_SYSTEM_FIELD_NEXIST);
            }

            Validate(DynamicFrom::class)->scene('edit')->check($param);


            $fData = $this->systemDynamicFrom->editFromModel($param);

            $fid = $fData['id'];

            //先删除 再添加
            $this->systemDynamicFromField->delFieldModel(['fid' => $fid,'attribute'=>1]);
            //静态固定字段拼接模板id 写入字段库
            $this->systemDynamicFromField->addFieldAllModel($system->systemFieldMontage($data, $fid));
            //添加操作日志
            $this->operateLog->addOperate($request->param('user_login_id'), message::$TRENDS_FROM, message::$SUCC_SYSTEM_UPDATE_TRENDS);

            DbAlias::commit();
        } catch (ValidateException $e) {
            DbAlias::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }


        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);


    }

    //添加动态表单数据
    public function addFromData(Request $request, System $system)
    {
        /**
         * @param $template_name
         * @param $type
         * @param $alias_id //关联menu表alias_id
         *
         */
        $param = $request->post();
        DbAlias::startTrans();

        try {
//            Validate(DynamicFrom::class)->check($param);

            //查询别名是否存在
            if ($this->systemDynamicFrom->getAliasIdEx($param['alias_id'])) {
                return ReJson(message::$ERROR_CODE, message::$ERR_ALIAS_ID_EXIST);
            }

            //查询别名对应模板系统字段
            $ReflectionClass = new ReflectionClass(databaseField::class);

            $data = $ReflectionClass->getStaticPropertyValue($param['alias_id'], false);

            if (!$data) {
                return ReJson(message::$ERROR_CODE, message::$ERR_SYSTEM_FIELD_NEXIST);
            }

            //添加模板数据
            $fData = $this->systemDynamicFrom->addFromModel($param);

            $fid = $fData['id'];

            //静态固定字段拼接模板id 写入字段库
            $this->systemDynamicFromField->addFieldAllModel($system->systemFieldMontage($data, $fid));

            // 提交事务
            DbAlias::commit();
        } catch (ValidateException|Exception $e) {
            // 回滚事务
            DbAlias::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        $this->operateLog->addOperate($request->param('user_login_id'), message::$TRENDS_FROM, message::$SUCC_SYSTEM_ADD_TRENDS);
        return ReJson(message::$SUCC_CODE, message::$SUCC_INSERT_DATA);

    }


    //获取三级菜单列表
    public function getLevelMenu()
    {
        $menuList = $this->systemMenu->getTypeMenuModel();

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $menuList);
    }

    //删除模板
    public function delFromData(Request $request, System $systemService)
    {
        /**
         * @param $id
         */

        $id = $request->post('id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //先查询该模板是否有生产数据，存在否定删除
        $produceData = $this->systemDynamicFromField->getTmpFieldList($id);

        if (!empty($produceData)) return ReJson(message::$ERROR_CODE, message::$ERR_PERDUCE_DATA_DELETE);

        $result = $this->systemDynamicFrom->delFromModel($id);

        if ($result) {
            $this->operateLog->addOperate($request->param('user_login_id'), message::$TRENDS_FROM, message::$SUCC_SYSTEM_DELETE_TRENDS);
            return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
        }

        return ReJson(message::$ERROR_CODE, message::$ERR_DATELE_DATA);

    }

    //动态表单启用|禁用
    public function EnableDisableMenuTem(Request $request, SystemDynamicFrom $from)
    {
        $param = $request->post();

        try {

            Validate(\app\validate\SystemDynamicFromField::class)->scene('eDField')->check($param);

            $from->editFromModel($param);

        } catch (ValidateException|\Exception $e) {

            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        $this->operateLog->addOperate($request->param('user_login_id'), message::$TRENDS_FROM, message::$SUCC_SYSTEM_TRENDS_STATUS_DE);

        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    /*************************************************************字段管理********************************************************/

    //查看当前模板字段
    public function getTmpField(Request $request, UserPosition $position, UserOrganization $organization, User $user)
    {
        /**
         * @param $fid
         */
        $fid = $request->get('fid');
        $pageNum = $request->get('pageNum') ?: stateData::$_page;

        $page = $request->get('page') ?: 1;

        $name = $request->get('where');

        if (empty($fid)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $result = $this->systemDynamicFromField->getTmpFieldPage($fid, $page, $pageNum,$name);
        //查询可见范围
        //可见范围拼接nameStr


        foreach ($result as $i => $iValue) {
            $nameStr = '';
            //查询每个字段下可查看的人员/角色/部门
            $fieldPower = $this->systemFieldPower->getFieldPowerModel($iValue['id'], stateData::$_power_type['field']);
            //根据account_type寻找对应数据表查找权限人员name
            $str = '';
            foreach ($fieldPower as $jValue) {
                if (empty($jValue['account_type'])) break;

                //根据account_type寻找对应UserPosition数据表
                /** @noinspection TypeUnsafeComparisonInspection */
                if ($jValue['account_type'] == stateData::$_power_from_identifying['position']) {
                    //查找权限人员name
                    $str .= $position->getLevelName($jValue['roles_id']);


                    if (!empty($str)) {
                        $nameStr .= $str . ',';
                        unset($str);
                    }
                }

                /** @noinspection TypeUnsafeComparisonInspection */
                //根据account_type寻找对应UserOrganization数据表
                if ($jValue['account_type'] == stateData::$_power_from_identifying['organization']) {
                    //查找权限人员name
                    $str = $organization->getStructureName($jValue['roles_id']);

                    if (!empty($str)) {
                        $nameStr .= $str . ',';
                        unset($str);
                    }
                }

                /** @noinspection TypeUnsafeComparisonInspection */
                //根据account_type寻找对应user数据表
                if ($jValue['account_type'] == stateData::$_power_from_identifying['people']) {
                    //查找权限人员name
                    $str = $user->getIdName($jValue['roles_id']);

                    if (!empty($str)) {
                        $nameStr .= $str . ',';
                        unset($str);
                    }
                }

            }
            $result[$i]['name_str'] = rtrim($nameStr,',');
        }

        $pages['pageNumber'] = $pageNum;
        $pages['total'] = $this->systemDynamicFromField->getTmpFieldCount($fid);

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result, $pages);
    }

    //添加模板字段
    public function addTmpField(Request $request, System $systemService, SystemFieldRandPower $randPower)
    {
        /**
         * @param  $name
         * @param  $alias_field_id
         * @param  $fid
         * @param  $type
         * @param  $is_input
         * @param  $default_val //选填
         *
         * @param  $position string 角色权限内容 选填
         * @param  $organization string 角色架构权限内容  选填
         * @param  $people string  个人权限内容  选填
         */

        $param = $request->post();

        DbAlias::startTrans();
//        \think\facade\Log::error ($param);
        try {
//            Validate(\app\validate\SystemDynamicFromField::class)->check($param);

            //json序列化
            if (!empty($param['type_value'])) {
                $param['type_value'] = json_encode($param['type_value']);
            }
            //添加自定义字段
            $id = $this->systemDynamicFromField->addFieldModel($param);
//            //字段id
//            $param['id'] = $result->id;

//            \think\facade\Log::error ($param);
            $param['id'] = $id;

            //如果有角色权限传入
            $systemService->isPostPower($param);
            $randPower->addDataModel([
                'position' => $param['position'],
                'people' => $param['people'],
                'organization' => $param['organization'],
                'field_id' => $id,
            ]);

            // 提交事务
            DbAlias::commit();
        } catch (ValidateException|\Exception $e) {
            DbAlias::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        $this->operateLog->addOperate($request->param('user_login_id'), message::$TRENDS_FROM, message::$SUCC_SYSTEM_ADD_TRENDS_FIELD);

        return ReJson(message::$SUCC_CODE, message::$SUCC_INSERT_DATA);

    }

    //修改模板字段
    public function editTmpField(Request $request, System $systemService, SystemFieldRandPower $randPower)
    {

        /**
         * @param  $id //字段表id
         * @param  $name
         * @param  $alias_field_id
         * @param  $fid
         * @param  $type
         * @param  $is_input
         * @param  $default_val //选填
         *
         * @param  $position string 角色权限内容 选填
         * @param  $organization string 角色架构权限内容  选填
         * @param  $people string  个人权限内容  选填
         */

        $param = $request->post();

        DbAlias::startTrans();

        try {
            Validate(\app\validate\SystemDynamicFromField::class)->scene('edit')->check($param);

            if ($param['attribute'] == '系统字段'){
                $param['attribute'] = 1;
                //修改模板字段库基本字段信息
                $this->systemDynamicFromField->updateFieldModel($param);
                //修改字段可见权限 先删除再批量添加
                $systemService->isPostPower($param);
            }else{
                $param['type_value'] = json_encode($param['type_value']);
                $param['attribute'] = 2;
                //修改模板字段库基本字段信息
                $this->systemDynamicFromField->updateFieldModel($param);
                //修改字段可见权限 先删除再批量添加
                $systemService->isPostPower($param);
            }

            $data = [
                'position' => $param['position'],
                'people' => $param['people'],
                'organization' => $param['organization'],
                'field_id'=>$param['id']
            ];

            if (empty($param['position']) && empty($param['people']) && empty($param['organization'])){
                $randPower->delFieldIdData($param['id']);
            }else{
                $randPower->editFieldIdData($param['id'], $data);
            }


            DbAlias::commit();
        } catch (ValidateException|Exception $e) {
            DbAlias::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        $this->operateLog->addOperate($request->param('user_login_id'), message::$TRENDS_FROM, message::$SUCC_SYSTEM_UPDATE_TRENDS_FIELD);

        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);

    }

    /**
     * 查看字段详情
     * @param \app\Request $request
     * @param \app\model\SystemFieldRandPower $randPower
     * @return false|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getEditField(Request $request, SystemFieldRandPower $randPower, System $system)
    {
        $id = $request->get('id');

        if (empty($id)) ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $result = $this->systemDynamicFromField->getFieldDetails($id);
        //待优化
        $fieldData = $randPower->getFieldIdData($id);

        if (!empty($fieldData)) {

            $result['people'] = $system->analysisId($fieldData['people']);
            $result['position'] = $system->analysisId($fieldData['position']);
            $result['organization'] = $system->analysisId($fieldData['organization']);

        } else {

            $result['people'] = [];
            $result['position'] = [];
            $result['organization'] = [];
        }


        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    //删除模板字段
    public function delTmpField(Request $request)
    {
        /**
         * @param $fld //字段表id
         */

        $fid = $request->post('fid');

        if (empty($fid)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //查询是否有字段权限记录产生，如果有不让删除
        $fieldPower = $this->systemFieldPower->getFieldPowerModel($fid, stateData::$_power_type['field']);

        if (!empty($fieldPower)) return ReJson(message::$ERROR_CODE, message::$ERR_FIELD_POWER_DELETE);

        DbAlias::starttrans();

        try {
            //删除字段表
            $this->systemDynamicFromField->delFieldModel($fid);

            $this->systemFieldPower->delFieldPowerModel($fid);

            DbAlias::commit();

        } catch (Exception $e) {

            DbAlias::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());

        }
        $this->operateLog->addOperate($request->param('user_login_id'), message::$TRENDS_FROM, message::$SUCC_SYSTEM_DELETE_TRENDS_FIELD);

        return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);

    }

    //动态表单字段启用|禁用
    public function EDTmpField(Request $request)
    {
        $param = $request->post();

        try {

            Validate(\app\validate\SystemDynamicFromField::class)->scene('eDField')->check($param);

            //判断当前是开就赋值为关 关赋值为开
//            $param['is_k'] == stateData::$_on_off['on'] ? $param['is_k'] = stateData::$_on_off['on'] : $param['is_k'] = stateData::$_on_off['off'];

            $this->systemDynamicFromField->updateFieldModel($param);

        } catch (ValidateException $e) {

            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        $this->operateLog->addOperate($request->param('user_login_id'), message::$TRENDS_FROM, message::$SUCC_SYSTEM_DELETE_TRENDS_FIELD_STATUS_DE);

        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    //获取字段类型select
    public function getSesVal()
    {
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, stateData::$_field);
    }

    //获取组织架构列表
    public function getOrganizationList(UserOrganization $organization, System $systemService)
    {

        $result = $systemService->menuTreeList($organization->getStructure());

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    //获取角色列表
    public function getPositionList(UserPosition $position)
    {
        $result = $position->getLevelList();

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    //获取部门所有人
    public function getUserAssList(User $user, UserOrganization $org, System $system, Request $request,UserOrganization $organization)
    {
        $id = $request->get('oid');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        $result = [];
        if($id != 'null'){
            $oidArr = $system->getOrgIdStr ($id,$organization->getStructure ());

            $idArr = $user->getUidArrDataModel ($oidArr);

            $result = $user->getUidArrNicknameModel($idArr);
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    //获取多部门下所有人
    public function getUserAssStrList(User $user, UserOrganization $org, System $system, Request $request)
    {
        $id = $request->get('oid');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $oidArr = explode (',',$id);
        //查询延伸子集
        $str = '';
        foreach ($oidArr as $item) {
            $str .= $system->getOrgIdStr($item,$org->getStructure ());
        }
        $result = $user->getOrgArrUidModel(rtrim ($str,','));

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    /**
     * 获取当前用户数据可见范围
     * 返回对应组织架构与人员
     * @param \app\Request $request
     * @param \app\model\User $user
     * @param \app\model\SystemMenuDataPower $dataPower
     * @return false|string|void
     */
    public function getDataPowerUid(Request $request,User $user,SystemMenuDataPower $dataPower,UserOrganization $org,System $system)
    {
        $uid = $request->get ('user_login_id');
        //获取当前用户职位等级
        $userData = $user->getIdUserData($uid);
        //通过等级获取数据可见范围
        $power = $dataPower->getDataRangeModel($userData['level_id']);
        $userOrganization = new UserOrganization();
        //通过数据权限寻找对应组织架构
        if ($uid == 1){ //admin
            $orgData = $org->getStructure();
            $orgTerr = $system->menuTreeList($orgData);
        }elseif($userData['type'] == 3){ //分支
//            $orgData = $system->getOrgIdStr($userData['department_id']['id'],$org->getStructure());
            $orgData = $userOrganization->getDataRangeDepartmentList([],$userData['department_id']['id']);
            $orgData[] = (int)$userData['department_id']['id'];
            //树形结构
            $orgTerr = $system->OrgParentTreeList($org->getOrgInNameModel($orgData),$userData['department_id']['id']);

        }else{
            if ($power == 1){//总公司 所有部门架构
                $orgData = $org->getStructure();
                $orgTerr = $system->menuTreeList($orgData);
            }elseif($power == 2){//分公司 当前部门往上推 找总公司下面全部
                $pid = $system->getOrgFgsId($userData['department_id']['id']);
//                $orgData = $system->getOrgIdStr($pid,$org->getStructure());
                $orgData = $userOrganization->getDataRangeDepartmentList([],$pid);
                $orgData[] = (int)$pid;

                //树形结构
                $orgTerr = $system->menuTreeList($org->getOrgInNameModel($orgData),$pid);
            }
            elseif($power == 3){//部门
                $pid = $userData['department_id']['id'];
                $orgData = $system->getOrgIdStr($pid,$org->getStructure());
                $pData = $org->getOrgInNameModel($orgData);
                $orgTerr =  $system->menuTreeList($pData,$pData[0]['parent_id']);

//                $orgData = $userOrganization->getDataRangeDepartmentList([],$pid);
//                $orgData[] = (int)$pid;
//                $pData = $org->getOrgInNameModel($orgData);
//                $orgTerr = $system->menuTreeList($org->getOrgInNameModel($orgData),$pid);

            }
            else{
                $orgTerr = '';
            }
        }

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$orgTerr);
    }

    /**
     * 获取登陆用户直属部门下组织架构id
     */
    public function getUidDepartmentData(Request $request,User $user,SystemMenuDataPower $dataPower,UserOrganization $org,System $system)
    {
        $uid = $request->get ('user_login_id');

        //获取当前用户信息
        $userData = $user->getIdUserData($uid);
        //获取所有分支
        $branchData = $user->getBranchDepartmentIds();
        $orgData = $org->getStructureArr ();
        $result = [];
        if (!empty($branchData)){
            //查询用户分支对应的部门id集合
            $orgArr = [];
            foreach ($branchData as &$branchDatum) {
                $orgDa = explode (',',rtrim ($system->getOrgIdStr($branchDatum['department_id']['id'],$orgData),','));
                foreach ($orgDa as $item) {
                    if ($userData['department_id']['id']  == $item){
                        $orgArr = $orgDa;
                        break;
                    }
                }
            }

            if ($orgArr){
                $result = $system->menuTreeList($org->getOrgInNameModel($orgArr));
            }
        }

        //如果分支为空 获取当前部门所有父级
        if (empty($result)){
            $orgId = rtrim ($system->getParentIdStr($userData['department_id']['id'],$orgData),',');
            $pidArr = explode (',',$orgId);
            $pid = $pidArr[count($pidArr)-1];
            $result = $system->menuTreeList($org->getOrgInNameModel($system->getOrgIdStr($pid,$orgData)));
        }

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$result);
    }

    //获取当前分支管理员
    public function getBranchManage(Request $request,User $user,SystemMenuDataPower $dataPower,UserOrganization $org,System $system)
    {
        $uid = $request->get ('user_login_id');
        //获取当前用户信息
        $userData = $user->getIdUserData($uid);
        $arr = [];
        if ($userData['department_id']['id']){
            //查询当前分支下所有人
            $orgUserData = $user->getOidUidSelectDataModel($userData['department_id']['id']);

            foreach ($orgUserData as $k =>$orgUserDatum) {
                $data = $dataPower->getPotionData($orgUserDatum['level_id']['id']);
                if ($data['data_range'] === 3){
                    $arr[$k] = $orgUserDatum;
                }
            }
            $arr = array_values ($arr);
        }
        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$arr);
    }

    //获取所有部门跟人员 带层级关系
    public function getOrgUidList(User $user, UserOrganization $org, System $system)
    {
        $orgModel = $org->getStructure();
        $result = $system->getOrgTypeUserList($orgModel);

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }


    //添加字段权限
    public function addFieldPower(Request $request, System $system, SystemDynamicFromField $systemDynamicFromField, SystemFieldRandPower $randPower)
    {
        /**
         * @param $people
         * @param $organization
         * @param $position
         */
        $param = $request->post();

        if (empty($param['id'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        //查询字段详情
//        $details= $systemDynamicFromField->getFieldDetails($param['id']);

        $field_id = $param['id'];
        unset($param['id']);

        try {
//            $system->isPostPower ($param);
            $randPower->editFieldIdData($field_id, $param);
        } catch (Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        $this->operateLog->addOperate($request->param('user_login_id'), message::$TRENDS_FROM, message::$SUCC_SYSTEM_DELETE_TRENDS_FIELD_ADD_POWER);

        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);

    }

    //获取当前账号管理员工
    public function getManageStaff(
        User    $user,
        Power   $power,
        Request $request,
        System  $system
    )
    {
        //查询用户数据范围
        $range = $power->getUserDataRange($request->param('user_login_id'));
        //根据条件查询用户范围
        $users = $user->getIdUserRandInfo($range);

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $users);
    }


    //获取菜单对应操作 页签等权限
    public function getUserAliasIdOp(
        Request $request,
        Power   $power
    )
    {
        $aliasId = $request->get('aliasId');

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $result = $power->getBUttonPower($aliasId, $request->param('user_login_id'));
//        //获取用户权限
//        $userInfo = $user->getIdUserData($request->get ('user_login_id'));
//
//        //通过用户绑定职位获取菜单级可见范围
//        $userMenuPower = $menuPower->getPositionDataDetails ($userInfo['level_id']);
//
//        //获取菜单权限
//        $id = $menu->getAliasIdMenu($aliasId);
//
//        $ops = $menu->getAliasIdSonDataModel($id[0]);
//
//        $result = $system->powerPoint(
//            $ops,
//            $system->analysisId ($userMenuPower['menu_alias_id']),
//            'alias_id',
//            'menu_alias_id'
//        );

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }



    /***************************************************************公告管理******************************************************/

    //添加系统公告
    public function addNotice(Request $request, SystemNotice $notice)
    {
        $param = $request->post();

        if (empty($param['content'])) return ReJson (message::$ERROR_CODE,message::$EMPTY_CONTENT);

        $param['sort'] = $notice->getCountModel() + 1;
        $notice->addDataModel($param);

        return ReJson(message::$SUCC_CODE, message::$SUCC_INSERT_DATA);
    }


    //删除系统公告
    public function delNotice(Request $request, SystemNotice $notice)
    {
        $id = $request->post('id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        try {
            $data = explode(',', $id);

            if (is_array($data)) foreach ($data as $datum) {

                $notice->delId($datum);
            }
        } catch (\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
    }

    //查看公告
    public function getNotice(Request $request, SystemNotice $notice)
    {
        $page = $request->get('page') ?: 1;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        $type = $request->get('type') ?: 1;

        $param = $request->get();

        $where = [];
        if (isset($param['content']) & !empty($param['content'])) {

            $where[] = ['content', 'like', '%' . $param['content'] . '%'];
        }

        $result = $notice->getPageDataModel($page, $pageNum, $type, $where);

        $pages['total'] = $notice->getDataCountModel($type, $where);
        $pages['pageNum'] = $pageNum;
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result, $pages);
    }


    //编辑公告
    public function editNotice(Request $request, SystemNotice $notice)
    {
        $param = $request->post();

        if (empty($param['id'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $notice->editId($param);

        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    /**
     * 单文件上传 返回url地址
     * @param \app\Request $request
     * @return false|string
     */
    public function fileUp(Request $request)
    {
        $file = $request->file('file');
        $fileDz = '';
        if ($file){
            $fileDz = \think\facade\Filesystem::disk('public')->putFile( 'file', $file);
        }

        return ReJson (message::$SUCC_CODE,message::$SUCC_OPERATE,str_replace('\\', '/', 'http://' . $_SERVER['HTTP_HOST'] . '/storage/' . $fileDz));
    }

    /**
     * 关联客户名称
     * 查询企业 人才姓名
     */
    public function getCustom(Request $request,CluePerson $cluePersonModel,\app\model\ClueEnterprise $clueEnterpriseModel)
    {
        $name = $request->get ('name');
        //获取所有人才姓名
        $person_name = $cluePersonModel->getAllPersonNameDataModel($name);

        $enter_name = $clueEnterpriseModel->getEnterNameDataModel($name);

        foreach ($enter_name as $item) {
            $person_name[] = $item;
        }

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,assoc_unique ($person_name,'title'));
    }

    /**
     * 查询证书子集
     */
    public function getCerChilds(Request $request,SystemCertificate $systemCertificateModel)
    {
        $id = $request->get ('id');

        if ($id){
            $result = $systemCertificateModel->getIdSubClass($id);
        }else{
            $result = $systemCertificateModel->getIdSubClass(0);
        }
        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$result);
    }

}
